<?php
class Users extends MY_Controller
{
	var $curl = 'users';
	var $name = '';
	var $search = '';
	var $per_page = 0;
	var $language;
	var $submenu = "_menu";
	var $id_user = '';
	
	function __construct()
	{
		parent::__construct();
		$this->load->model(array('/public/user_model', '/public/geo_state_model', 
								 '/public/geo_city_model','public/geo_country_model',
								 '/public/inbox_model','/public/friends_model'));

		$this->validation->set_fields($this->user_model->fields);
		$this->data['Title'] = T_('Users');		

		$this->language = parent::getLang();

		$this->name = T_('Users');
	}
	
	function index()
	{
        $this->user_model->search();
     	$this->renderLayout();
	}

	function search_autocomplete()
	{
		echo $this->user_model->search_autocomplete();
	}
	
	function create()
	{
		if (!empty($_POST))
		{
			$rules = array('first_name', 'last_name', 'phone', 'password',  'password_confirm', 'status', 'acl_role','email');
			
			$country = $_POST['country_ID'];

            if($country == "840"){
                $rules[]='state_ID';
            }else if($country!=="0"){
                $rules[]='province';
            }
            
			$this->validation->set_rules($this->user_model->getRules($rules));
					
			$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("User").'»</span> '.T_("already exists with such email. Please change the email."));								
			
			if ($this->validation->run() === TRUE)
			{				
				$item['user_first_name'] 		= $this->validation->first_name;
				$item['user_last_name']			= $this->validation->last_name;
				$item['user_phone'] 			= $this->validation->phone;
				$item['user_email'] 			= $this->validation->email;
				$item['user_password'] 			= $this->validation->password;	
				$item['user_id_acl_roles'] 		= $this->validation->acl_role;				
				$item['user_status'] 			= $this->validation->status;
				
				//not required
				if($country=='840'){
                    $states 					= $this->geo_state_model->getSelectOptions($user_country_ID);
                    $user_state          		= $states[$this->validation->state_ID];

                }else{
                    $user_state          		= $this->validation->province;
                }
				$item['user_country_ID'] 		= ($this->validation->country_ID == '')?'':$this->validation->country_ID;
				$item['user_state'] 			= $user_state;
				
				$paymentMethod      			= $this->config->item('paymentMethod');
                $item['user_payment_method']	= ($this->validation->payment_method == '0')?'':$paymentMethod[$this->validation->payment_method];

                $userCard                		= $this->config->item('cardTypeitem');       
                $item['user_card_type']         = ($this->validation->card_type == '0' || $this->validation->card_type == '')?'':$userCard[$this->validation->card_type];
                $item['user_card_number'] 		= ($this->validation->card_number == '')?'':$this->validation->card_number;
 
				$item['user_city'] 				= ($this->validation->city == '')?'':$this->validation->city;
				$item['user_address'] 			= ($this->validation->address == '')?'':$this->validation->address;
				$item['user_zip_code'] 			= ($this->validation->address == '')?'':$this->validation->zip_code;
				$item['user_security_code'] 	= ($this->validation->security_code == '')?'':$this->validation->security_code;
				
				$userMonth               		= $this->config->item('months');
                $item['user_exp_month']         = ($this->validation->exp_month == '0' || $this->validation->exp_month == '')?'':$userMonth[$this->validation->exp_month];
                $userYear                		= $this->config->item('expYearitem');
                $item['user_exp_year']          = ($this->validation->exp_year == '0' || $this->validation->exp_year == '')?'':$userYear[$this->validation->exp_year];
				
       			if ($this->user_model->insert($item))
       			{	
					// Save User Roles
					//$this->db->insert('users_roles', array('id_users' => $id_user, 'id_roles' => ROLE_CONTRIBUTOR, 'id_group' => CONTRIBUTOR_GROUP_ID));
					
         			redirect($this->curl . '/index'); 
       			}				
			}
		}
		else
		{
			//$this->validation->phone = 'some';
		}
		
		$this->data['Title'] .= ' / ' . T_('New User');
		
		$this->renderLayout();			
	}
	
	function edit($id = null)
	{
		if (!empty($id))
		{
			$object = $this->user_model->get($id);
			$this->data['country_ID'] = $object['user_country_ID'];
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false; 
			}
                			
			if (!count($_POST))
			{
				//pr($object);
				$this->validation->id 					= $object['user_ID'];
				$this->validation->first_name 			= $object['user_first_name'];
				$this->validation->last_name 			= $object['user_last_name']; 
				$this->validation->phone 				= $object['user_phone'];
				$this->validation->email 				= $object['user_email'];
				$this->validation->acl_role				= $object['user_id_acl_roles'];
				$this->validation->status 				= $object['user_status'];
				$this->validation->password 			= '';
				$this->validation->password_confirm 	= '';
				
				$this->validation->country_ID 			= $object['user_country_ID'];
				$this->validation->state 				= $object['user_state'];
				
				if($this->validation->country_ID == "840"){
	                $rules[]='state_ID';
	                $this->validation->state_ID = $object['user_state'];
	            }else if($this->validation->country_ID!=="0"){
	                $rules[]='province';
	                $this->validation->province = $object['user_state'];
	            }
				
				$this->validation->payment_method 		= '0'; 
				foreach($this->config->item('paymentMethod') as $key => $value) {
					if($value == $object['user_payment_method']){
						$this->validation->payment_method = $key;
					}
				}
				
				$this->validation->card_type 			= '0'; 
				foreach($this->config->item('cardTypeitem') as $key => $value) {
					if($value == $object['user_card_type']){
						$this->validation->card_type = $key;
					}
				}
                
				$this->validation->card_number 			= $object['user_card_number'];
				
				$this->validation->city 				= $object['user_city'];
				$this->validation->address 				= $object['user_address'];
				$this->validation->zip_code 			= $object['user_zip_code'];
				$this->validation->security_code 		= $object['user_security_code'];
 				
				foreach($this->config->item('months') as $key => $value) {
					if($value == $object['user_exp_month']){
						$this->validation->exp_month = $key;
					}
				}
				foreach($this->config->item('expYearitem') as $key => $value) {
					if($value == $object['user_exp_year']){
						$this->validation->exp_year = $key;
					}
				}
			}
			else
			{				
				$rules = array('first_name', 'last_name', 'phone', 'status', 'acl_role');
				
				$country = $_POST['country_ID'];
	
	            if($country == "840"){
	                $rules[]='state_ID';
	            }else if($country!=="0"){
	                $rules[]='province';
	            }
	            
	            $password = $_POST['password'];
	            $password_confirm = $_POST['password_confirm'];
				if($password != '' && $password_confirm != ''){
	                $rules[]='password';
	                $rules[]='password_confirm';
	            }
	            
	            
				$this->validation->set_rules($this->user_model->getRules($rules));
						
				$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("User").'»</span> '.T_("already exists with such email. Please change the email."));								
				
				if ($this->validation->run() === TRUE)
				{				
					$item['user_first_name'] 		= $this->validation->first_name;
					$item['user_last_name']			= $this->validation->last_name;
					$item['user_phone'] 			= $this->validation->phone;
					$item['user_email'] 			= $this->validation->email;
					$item['user_password'] 			= $this->validation->password;	
					$item['user_id_acl_roles'] 		= $this->validation->acl_role;				
					$item['user_status'] 			= $this->validation->status;
					
					//not required
					if($country=='840'){
	                    $states 					= $this->geo_state_model->getSelectOptions($user_country_ID);
	                    $user_state          		= $states[$this->validation->state_ID];
	
	                }else{
	                    $user_state          		= $this->validation->province;
	                }
					$item['user_country_ID'] 		= ($this->validation->country_ID == '')?'':$this->validation->country_ID;
					$item['user_state'] 			= $user_state;
					
					$paymentMethod      			= $this->config->item('paymentMethod');
	                $item['user_payment_method']	= ($this->validation->payment_method == '0')?'':$paymentMethod[$this->validation->payment_method];
	
	                $userCard                		= $this->config->item('cardTypeitem');       
	                $item['user_card_type']         = ($this->validation->card_type == '0' || $this->validation->card_type == '')?'':$userCard[$this->validation->card_type];
	                $item['user_card_number'] 		= ($this->validation->card_number == '')?'':$this->validation->card_number;
	 
					$item['user_city'] 				= ($this->validation->city == '')?'':$this->validation->city;
					$item['user_address'] 			= ($this->validation->address == '')?'':$this->validation->address;
					$item['user_zip_code'] 			= ($this->validation->address == '')?'':$this->validation->zip_code;
					$item['user_security_code'] 	= ($this->validation->security_code == '')?'':$this->validation->security_code;
					
					$userMonth               		= $this->config->item('months');
	                $item['user_exp_month']         = ($this->validation->exp_month == '0' || $this->validation->exp_month == '')?'':$userMonth[$this->validation->exp_month];
	                $userYear                		= $this->config->item('expYearitem');
	                $item['user_exp_year']          = ($this->validation->exp_year == '0' || $this->validation->exp_year == '')?'':$userYear[$this->validation->exp_year];
					
	       			
	                $item['user_ID'] 				=  $this->validation->id;

	                if ($this->user_model->update($item))
	       			{	
						// Save User Roles
						//$this->db->insert('users_roles', array('id_users' => $id_user, 'id_roles' => ROLE_CONTRIBUTOR, 'id_group' => CONTRIBUTOR_GROUP_ID));
						
	         			redirect($this->curl . '/index'); 
	       			}				
				}
			}	
		}
        	
		$this->data['Title'] .= ' / ' . T_('Edit');
		
		$this->renderLayout();
	}
	
	function account($id)
	{		
        $sql = "SELECT * 
                FROM stats.users_payments 
                WHERE id_users=".$this->db->escape($id)." 
                ORDER BY id DESC";
        $this->data['history'] = $this->db->query($sql)->result();
        		
		if (count($_POST))
		{			
			
			$rules = array('amount','notes');
			$this->validation->set_fields($this->accountuser_model->fields);
			$this->validation->set_rules($this->accountuser_model->getRules($rules));
			$this->validation->set_message('__positiveNumbers', '<span class="black bold">........');
						

			if ($this->validation->run() === TRUE)
			{			
								
				$item['id_users']		= $id;
				$item['dt']				= date('Y-m-d H:i:s');
				$item['type']			= 0;
				$item['notes']			= $this->validation->notes;	
				
				$item['amount'] = ($_POST['action'] == 'РћС‚РЅСЏС‚СЊ')
				?(-1*$this->validation->amount)
				:(1*$this->validation->amount);
					
						
				if ($this->accountuser_model->insert($item))
				{
					/*$sql = "SELECT nextval('advertisers_id_seq')";
					$sequence = $this->db->query($sql)->row();
					$id_advertiser = $sequence->nextval - 1;
					
					// Save User Roles					
					$this->db->insert('users_roles', array('id_users' => $id_advertiser, 'id_roles' => ROLE_COMPANY, 'id_group' => COMPANY_GROUP_ID));						
				*/	
					//Save User Bonus
			        /* $this->db->insert('stats.advertisers_payments', array('id_advertisers' => $id, 'dt' =>  date('Y-m-d H:i:s'), 'type' => 0, 
										'amount' => $var_amount, 'notes' => $this->validation->notes));
					*/
					redirect($this->curl . '/edit/'.$id);	
				}				
			}
		}
				
		$this->data['Title'] = 'РџРѕРїРѕР»РЅРёС‚СЊ СЃС‡РµС‚';
		$this->validation->id = $id;		
		
		$this->renderLayout();			
	}
	
	function stat($id = 0)
	{				
		if (!empty($id))
		{
			$object = $this->user_model->get($id);
			$this->data['Title'] = $this->name . ' / ' . T_('Р¤РёРЅР°РЅСЃС‹ Рё СЃС‚Р°С‚РёСЃС‚РёРєР°');					
		}
		
		$this->data['id']   	  = $id;
		$this->data['date_start'] = $this->input->post('date_start');
		$this->data['date_end']   = $this->input->post('date_end');
		
		$this->user_model->stat($id);
		
		$this->user_model->table_stat($id);
		
		$this->renderLayout();
	}
		
	function deleteItems()
	{
        $data = $this->user_model->delete($_REQUEST['items']);
        echo $data;
	}

  function delete($id)
  {
    $data = $this->user_model->delete($id);

    redirect($this->curl . '/index');
  }

  function deleteFrItems()
	{
        $data = $this->friends_model->delete($_REQUEST['items']);
        echo $data;
	}

  function deleteFr($id,$user_id)
  {
    $data = $this->friends_model->delete($id);
    redirect($this->curl . '/friends/'.$user_id);
  }


	function activity()
	{
		$data = $this->utils->publishItems($this->user_model->table, $this->user_model->prKey, $this->user_model->publishedField, $_REQUEST['items'], $_REQUEST['action']);
		echo $this->utils->php2js($data);
	}
		
  function __loginFree($login = null)
  { 
    return $this->user_model->loginFree($login);
  }

  function __phoneFree()
  {   
    if (!empty($this->data['ani']))
    {
        foreach ($this->data['ani'] as $phone)
        {
            $res = $this->user_model->phoneFree($phone);
            if (!$res)
            {
            	$this->validation->set_message('__phoneFree', 'Р’РІРµРґРµРЅРЅС‹Р№ <span class="black bold">«РќРѕР�?РµСЂ С‚РµР»РµС„РѕРЅР°»</span> СѓР¶Рµ Р·Р°РЅСЏС‚ РІ Р±Р°Р·Рµ');            	
                return false;
            }
        }
        
        return true;
    }
    else
    {
        $this->validation->set_message('__phoneNumber', 'РќРµРѕР±С…РѕРґРёР�?Рѕ РґРѕР±Р°РІРёС‚СЊ <span class="black bold">«РќРѕР�?РµСЂ С‚РµР»РµС„РѕРЅР°»</span>');
        return false;
    }
  }
    
  function __phoneValid()
  {   
    if (!empty($this->data['ani']))
    {
        foreach ($this->data['ani'] as $phone)
        {
            if (!preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $phone))
            {
            	echo $phone;
            	$this->validation->set_message('__phoneValid', 'РќРµРІРµСЂРЅС‹Р№ С„РѕСЂР�?Р°С‚ РїРѕР»СЏ <span class="black bold">«РќРѕР�?РµСЂ С‚РµР»РµС„РѕРЅР°»</span>. Р”РѕРїСѓСЃС‚РёР�?С‹Рµ СЃРёР�?РІРѕР»С‹ - С‚РѕР»СЊРєРѕ С†РёС„СЂС‹.');
            }
        }
        
        return true;
    }
  }
  
	function details()
	{
		$id = $this->auth->getID();
		//does the object exist?
		if (!empty($id))
		{
			$object = $this->user_model->get($id);
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false; 
			}
			
			if (!count($_POST))
			{
				//passing data
				$this->validation->user_ID 		= $object['user_ID'];
				$this->validation->user_login 	= $object['user_login']; 
				$this->validation->user_name 	= $object['user_name']; 
				$this->validation->user_email 	= $object['user_email'];
				$this->validation->user_phone 	= $object['user_phone'];
				$this->validation->user_password = $object['user_password'];							 
			}
			else
			{
				$rules = array('user_login', 'user_password', 'user_name', 'user_email', 'user_phone');
				$this->validation->set_rules($this->user_model->getRules($rules));
	
				if ($this->validation->run() === TRUE)
				{
					//prepare data
					$item['user_ID'] = $this->validation->user_ID;
					$item['user_login'] = $this->validation->user_login;
					$item['user_password'] = $this->validation->user_password;					
					$item['user_name'] = $this->validation->user_name;
					$item['user_email'] = $this->validation->user_email;
					$item['user_phone'] = $this->validation->user_phone;					
					
					$this->user_model->update($item);
					
					redirect($this->curl . '/index');
				}
			}	
		}
	
		$this->view 	= $this->curl . '/details';
		$this->renderLayout();
	}	
	
	function finance()
	{		
		$id = $this->auth->getID();
		
		if (!empty($id))
		{
			$object = $this->user_model->get($id);
		}
		
		$this->user_model->stat($id);
		$this->user_model->table_stat($id);
		
		$this->data['Title'] = T_('Р В¤Р С�?Р Р…Р В°Р Р…РЎРѓРЎвЂ№ Р С�? РЎРѓРЎвЂљР В°РЎвЂљР С�?РЎРѓРЎвЂљР С�?Р С”Р В°');	
		
		$this->renderLayout();
	}
	function send($id) {
		if($id !== null && isset($id)) {
			$this->data['id'] = $id;
			if (!empty($_POST)){
				
				$rules = array('message_header', 'message_text');
				
	            
				$this->validation->set_rules($this->inbox_model->getRules($rules));
				
				if ($this->validation->run() === TRUE)
				{				
					$item['inbox_user_ID'] 			= $id;
					$item['inbox_date_posted']		= date('Y-m-d H:i:s');
					$item['inbox_status'] 			= 7;
					$item['inbox_sender'] 			= 'HN';
					$item['inbox_message_header'] 	= $this->validation->message_header;	
					$item['inbox_message_text'] 	= $this->validation->message_text;				
					
	       			if ($this->inbox_model->insert($item))
	       			{	
	         			redirect($this->curl); 
	       			}				
				}
			}
			
			$this->data['Title'] = $this->data['Title'].'/Send Message';
		
		} else {
			$this->view = $this->curl;
		}
		$this->renderLayout();
	}
    function friends($id){
        $this->data['id'] = $id;
        $this->data['friends']=$this->friends_model->search($id);
        $this->renderLayout();
    }
    function createFriend($id){
        $this->data['id'] = $id;
		if (!empty($_POST))
		{
			$rules = array('full_name', 'email', 'status');
            $this->validation->set_rules($this->friends_model->getRules($rules));
  			$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("User").'»</span> '.T_("already exists with such email. Please change the email."));

			if ($this->validation->run() === TRUE)
			{
				$item['uf_full_name'] 		= $this->validation->full_name;
				$item['uf_email'] 			= $this->validation->email;
				$item['uf_status'] 			= $this->validation->status;
                $item['uf_user_ID']         = $id;

                if ($this->friends_model->insert($item))
       			{
					redirect($this->curl . '/friends/'.$id);
       			}
			}
		}
		else
		{
			//$this->validation->phone = 'some';
		}

		$this->data['Title'] .= ' / ' . T_('New Friend');
    	$this->renderLayout();

    }
    function editFriend($friendId){
        if (!empty($friendId))
		{
			$object = $this->friends_model->get($friendId);
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false;
			}

			if (!count($_POST))
			{
				$this->validation->full_name 			= $object['uf_full_name'];
				$this->validation->email 				= $object['uf_email'];
				$this->validation->status 				= $object['uf_status'];
                $this->validation->id                   = $object['uf_user_ID'];
			}else{
				$rules = array('full_name', 'email', 'status');
				$this->validation->set_rules($this->friends_model->getRules($rules));
				$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("User").'»</span> '.T_("already exists with such email. Please change the email."));

				if ($this->validation->run() === TRUE)
				{
					$item['uf_full_name']    		= $this->validation->full_name;
					$item['uf_email']   			= $this->validation->email;
					$item['uf_status']              = $this->validation->status;
                    $item['uf_user_ID']             = $this->validation->id;
                    $item['uf_id']                  = $friendId;
                    
	                if ($this->friends_model->update($item))
	       			{
						redirect($this->curl . '/friends/'.$item['uf_user_ID']);
	       			}
				}
			}
		}

		$this->data['Title'] .= ' / ' . T_('Edit');
        $this->data['uf_id']  = $friendId;

		$this->renderLayout();
	}
}
?>